from PyQt5 import QtCore
from PyQt5 import QtCore
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QGridLayout, QHBoxLayout, QLabel, QLineEdit, QMessageBox, QPushButton, QVBoxLayout,QWidget
import sys
class tWindow(QWidget):
    
    def __init__(self) -> None:
        super().__init__()
        self.text = ''
        self.inittabUI() # 初始化界面方法
        
    def numys(self,str1):  # 对两个数进行操作
        return str(eval(str1))
    # def text_changed(self):
    #     print('改变了')
    def click(self): # 所有按钮的点击事件
        key = self.sender().text() # 获取所点击按钮的值
        # 如果输入的是运算符号，则清空文本框数据并记录
        if key in ('+','-','*','/'): # 根据值的不同来确定那个按钮被点击
            self.text = self.qline.text() # 获取文本框的值，进行追加
            self.text += key                  
            self.qline.setText(self.text)
        # 如果输入的是等于号，则将运算结果展示在文本框
        elif key in ('0','1','2','3','4','5','6','7','8','9','.'):            
            self.text = self.qline.text() # 获取文本框的值，进行追加
            self.text += key
            self.qline.setText(self.text)
        # 如果输入的Cls则将 数据清空
        elif key == 'Cls':
            self.qline.clear() #将所有值清空，将文本框的值设置成默认值
        elif key == 'Bck':
            text = self.qline.text()
            text = text[-len(text):-1] # 利用切片一直切到最后一位
            self.qline.setText(text)
        elif key == '=': 
            text = self.qline.text()  #如果点等于的话，直接获取文本框的数值
            sum = self.numys(text) # 进行运算
            self.qline.setText(sum)
    def inittabUI(self):
        # 添加文本框
        self.qline = QLineEdit()
        self.qline.setPlaceholderText('0')
        self.qline.setAlignment(QtCore.Qt.AlignRight)
        # self.qline.setEnabled(False)
        self.qline.setFocusPolicy(QtCore.Qt.NoFocus)
        grid = QGridLayout()
        self.setLayout(grid)
        names = ['Cls', 'Bck', 'CE', 'Close',
                 '7', '8', '9', '/',
                '4', '5', '6', '*',
                 '1', '2', '3', '-',
                '0', '.', '=', '+']
        positions = [(i,j) for i in range(1,6) for j in range(4)]
        
        grid.addWidget(self.qline,0,0,1,4)
        for position,name in zip(positions,names):
            button = QPushButton(name)
            button.clicked.connect(self.click)
            grid.addWidget(button, *position)
        # self.move(300, 150)
        self.setWindowTitle('Calculator')
        # self.setFixedSize(self.width(), self.height());  
        self.setWindowIcon(QIcon(r'D:\workspace\pyqt入门\b11.png'))
        self.show()
if __name__ == '__main__':
    app = QApplication(sys.argv)
    tw = tWindow()
    sys.exit(app.exec_())